package com.sky.cqculture.service.impl;

import com.sky.cqculture.Mapper.OrderItemMapper;
import com.sky.cqculture.Mapper.OrderMapper;
import com.sky.cqculture.Mapper.ProductMapper;
import com.sky.cqculture.Mapper.ShoppingCartMapper;
import com.sky.cqculture.pojo.Order;
import com.sky.cqculture.pojo.OrderItem;
import com.sky.cqculture.pojo.Product;
import com.sky.cqculture.pojo.ShoppingCart;
import com.sky.cqculture.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    @Transactional
    public Order createOrder(Integer userId, List<Integer> cartItemIds) {
        System.out.println("-----------------------------------------");
        // 1. 查询购物车商品
        List<ShoppingCart> cartItems = new ArrayList<>();
        double totalPrice = 0.0;
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            cartItems = shoppingCartMapper.findByUserId(userId);
        } else {
            for (Integer cartItemId : cartItemIds) {
                ShoppingCart cartItem = shoppingCartMapper.findById(cartItemId);
                if (cartItem != null && cartItem.getUserId().equals(userId)) {
                    cartItems.add(cartItem);
                }
            }
        }
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车为空，无法创建订单");
        }
        
        // 2. 计算订单总价
        for (ShoppingCart cartItem : cartItems) {
            Product product = productMapper.findById(cartItem.getProductId());
            if (product != null) {
                totalPrice += product.getPrice() * cartItem.getQuantity();
            }
        }
        
        // 3. 创建订单
        Order order = new Order(userId, totalPrice);
        Date now = new Date();
        order.setCreateTime(now);
        order.setUpdateTime(now); // 设置updateTime
        order.setStatus("已付款");
        orderMapper.add(order);
        
        // 4. 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (ShoppingCart cartItem : cartItems) {
            Product product = productMapper.findById(cartItem.getProductId());
            if (product != null) {
                OrderItem orderItem = new OrderItem(
                        order.getId(),
                        product.getId(),
                        cartItem.getQuantity(),
                        product.getPrice()
                );
                orderItem.setProductName(product.getName()); // 设置商品名称，将 getTitle() 替换为 getName() 以解决方法未定义问题
                orderItems.add(orderItem);
            }
        }
        
        if (!orderItems.isEmpty()) {
            orderItemMapper.batchAdd(orderItems);
        }
        
        // 5. 清空购物车
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            shoppingCartMapper.clear(userId);
        } else {
            // 只删除指定的购物车商品
            for (Integer cartItemId : cartItemIds) {
                shoppingCartMapper.deleteById(cartItemId);
            }
        }
        
        return order;
    }
    
    @Override
    public List<Order> getOrderList(Integer userId) {
        List<Order> orders = orderMapper.findByUserId(userId);
        // 为每个订单加载订单项
        for (Order order : orders) {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
            order.setOrderItems(orderItems);
        }
        return orders;
    }
    
    @Override
    public Order getOrderDetail(Integer orderId) {
        Order order = orderMapper.findById(orderId);
        if (order != null) {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(orderId);
            // 为每个订单项加载商品详情
            for (OrderItem orderItem : orderItems) {
                Product product = productMapper.findById(orderItem.getProductId());
                orderItem.setProduct(product);
            }
            order.setOrderItems(orderItems);
        }
        return order;
    }
    
    @Override
    public void payOrder(Integer orderId) {
        orderMapper.updateStatus(orderId, "已付款");
    }
}